package com.example.lw;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.webkit.WebView;
import android.widget.*;
import android.os.Bundle;
import android_serialport_api.SerialPort;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;

class Config {
    static String webUrl = "https://www.baidu.com/";
    static String ttyName = "/dev/ttyS0";
    static int ttyBaudrate = 9600;
    static int ttyFlag = 0;
}
public class MainActivity extends Activity {
    private VideoView videoView;
    static StringBuilder sb = new StringBuilder("");
    static AtomicBoolean flagTty = new AtomicBoolean(false);
    static AtomicBoolean flagCardTest = new AtomicBoolean(true);
    static AtomicBoolean flagPlayMedia = new AtomicBoolean(false);
    Handler handler1 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        hookWebView();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        Context context = this;
        //把声音调整为最大
        AudioManager am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
        am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_PLAY_SOUND);
        //音频测试循环播放, 开机播放两次 方便操作
        MediaPlayer mMediaPlayer;
        mMediaPlayer=MediaPlayer.create(this, R.raw.test);
        mMediaPlayer.setLooping(true);
        mMediaPlayer.start();
        Button amPlay = (Button) findViewById(R.id.button);amPlay.setOnClickListener(e->{
            if (flagPlayMedia.get()) {
                mMediaPlayer.pause();
            } else {
                mMediaPlayer.start();
            }
            flagPlayMedia.set(!flagPlayMedia.get());
        });

        //刷卡测试
        Button slotCardTest = (Button) findViewById(R.id.button4);
        slotCardTest.setOnClickListener((e)->{
            flagTty.set(true);
            slotCardTest.setText("请刷入卡片");
        });
        handler1 = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 2) {
                    slotCardTest.setText("卡片刷入功能正常，刷卡测试成功");
                }
            }
        };

        // 插卡测试
        Button cardTest = (Button) findViewById(R.id.button3);
        Handler handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    cardTest.setText("卡片插入功能正常,插卡测试成功");
                }
            }
        };
        final Thread thread = new Thread(() -> {
            while (flagCardTest.get()) {
                try {
                    synchronized (flagCardTest) {
                        CommandExecutionUtil.CommandResult commandResult = CommandExecutionUtil.execCommand("cat sys/class/gpio/gpio117/value ", true);
                        if ("1".equals(commandResult.successMsg)) {

                            Message msg = new Message();
                            msg.what = 1;
                            handler.sendMessage(msg);
                            flagCardTest.set(false);
                        } else {
                            flagCardTest.set(true);
                        }
                        flagCardTest.wait(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        cardTest.setOnClickListener(e->{
            flagCardTest.set(true);
            flagTty.set(true);
            thread.start();
            cardTest.setText("请插入卡片");
        });


//        videoView = (VideoView) findViewById(R.id.videoView);
//        videoView.setVideoURI(Uri.parse("android.resource://"+ getPackageName()+"/" + R.raw.start));
//        //videoView.setMediaController(new MediaController(this));
//        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
//            @Override
//            public void onPrepared(MediaPlayer mp) {
//                videoView.start();
//            }
//        });
//        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//            @Override
//            public void onCompletion(MediaPlayer mp) {
//                videoView.start();
//            }
//        });


        //网络测试
        WebView webView = (WebView) findViewById(R.id.webView);
        webView.loadUrl(Config.webUrl);

        //串口文字展示
        testCardReadertStart();

        //一些按钮绑定
        Button exit = (Button) findViewById(R.id.button2);exit.setOnClickListener(e->{EthernetUtil.setEthernetStaticIp(context, "192.0.0.101","255.255.255.0", "192.0.0.1","192.0.0.1");;System.exit(0);});
        // webview clear
        Button reStartNet = (Button) findViewById(R.id.button6);reStartNet.setOnClickListener(e->{
            webView.clearView();
            webView.loadUrl(Config.webUrl);
        });
        Button dhcp = (Button) findViewById(R.id.button10);dhcp.setOnClickListener(e->{EthernetUtil.setDynamicIp(context);});
        Button sta = (Button) findViewById(R.id.button11);sta.setOnClickListener(e->{EthernetUtil.setEthernetStaticIp(context, "192.0.0.101","255.255.255.0", "192.0.0.1","192.0.0.1");});
        // log save to "/data/日期戳"
        Button saveLog = (Button) findViewById(R.id.button12);saveLog.setOnClickListener(e->{
            showInputDialog();
        });
        Button success = (Button) findViewById(R.id.button8);success.setOnClickListener(e->{createLog("all success");EthernetUtil.setEthernetStaticIp(context, "192.0.0.101","255.255.255.0", "192.0.0.1","192.0.0.1");System.exit(0);});
        Button testSuf =(Button) findViewById(R.id.button13);testSuf.setOnClickListener(e->{
            context.startActivity(new Intent(context, TestActivity.class));
        });

        // 给界面染个色 做区分
        ConstraintLayout layout = (ConstraintLayout)findViewById(R.id.sbsb);
        layout.setBackgroundColor(Color.GRAY);
        TextView view = (TextView)findViewById(R.id.textView);
        view.setBackgroundColor(Color.YELLOW);

        //初始化以太网为dhcp
        EthernetUtil.setDynamicIp(context);

    }

    //dialog save log
    private void showInputDialog() {
        final EditText editText = new EditText(MainActivity.this);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(MainActivity.this);
        inputDialog.setTitle("Please enter the information").setView(editText);
        inputDialog.setPositiveButton("enter",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        createLog(editText.getText().toString());
                    }
                }).show();
    }

    //fix webview system_app error
    public void hookWebView(){
        int sdkInt = Build.VERSION.SDK_INT;
        try {
            Class<?> factoryClass = Class.forName("android.webkit.WebViewFactory");
            Field field = factoryClass.getDeclaredField("sProviderInstance");
            field.setAccessible(true);
            Object sProviderInstance = field.get(null);
            if (sProviderInstance != null) {
                Log.i("hookWebView","sProviderInstance isn't null");
                return;
            }
            Method getProviderClassMethod;
            if (sdkInt > 22) {
                getProviderClassMethod = factoryClass.getDeclaredMethod("getProviderClass");
            } else if (sdkInt == 22) {
                getProviderClassMethod = factoryClass.getDeclaredMethod("getFactoryClass");
            } else {
                Log.i("hookWebView","Don't need to Hook WebView");
                return;
            }
            getProviderClassMethod.setAccessible(true);
            Class<?> factoryProviderClass = (Class<?>) getProviderClassMethod.invoke(factoryClass);
            Class<?> delegateClass = Class.forName("android.webkit.WebViewDelegate");
            Constructor<?> delegateConstructor = delegateClass.getDeclaredConstructor();
            delegateConstructor.setAccessible(true);
            if(sdkInt < 26){//低于Android O版本
                Constructor<?> providerConstructor = factoryProviderClass.getConstructor(delegateClass);
                if (providerConstructor != null) {
                    providerConstructor.setAccessible(true);
                    sProviderInstance = providerConstructor.newInstance(delegateConstructor.newInstance());
                }
            } else {
                Field chromiumMethodName = factoryClass.getDeclaredField("CHROMIUM_WEBVIEW_FACTORY_METHOD");
                chromiumMethodName.setAccessible(true);
                String chromiumMethodNameStr = (String)chromiumMethodName.get(null);
                if (chromiumMethodNameStr == null) {
                    chromiumMethodNameStr = "create";
                }
                Method staticFactory = factoryProviderClass.getMethod(chromiumMethodNameStr, delegateClass);
                if (staticFactory!=null){
                    sProviderInstance = staticFactory.invoke(null, delegateConstructor.newInstance());
                }
            }

            if (sProviderInstance != null){
                field.set("sProviderInstance", sProviderInstance);
                Log.i("hookWebView","Hook success!");
            } else {
                Log.i("hookWebView","Hook failed!");
            }
        } catch (Throwable e) {
            Log.w("hookWebView",e);
        }
    }

    //go to setting reset factory
    public static void factoryReset (Context context) {
        Intent intent =
                new Intent(Settings.ACTION_PRIVACY_SETTINGS);
        context.startActivity(intent);
    }

    //cat log function API
    public static void createLog (String Text) {
        StringBuffer buffer = new StringBuffer();
        for (String str : new Date().toString().split(" ")){
            buffer.append(str.concat("_"));
        }
        buffer.deleteCharAt(buffer.length()-1);
        CommandExecutionUtil.execCommand("echo ".concat(Text.concat(" >> /data/".concat(buffer.toString()))),true);
    }

    // 对读卡器接口进行测试的初始化操作
    public void testCardReadertStart () {

        final SerialPort serialPort;
        try {
            //初始化串口ttyS0 定制可以自己改动
            serialPort = new SerialPort(new File(Config.ttyName), Config.ttyBaudrate, Config.ttyFlag);
        } catch (IOException e) {
            Log.i("llsz","io is error");
            e.printStackTrace();
            System.exit(0);
            return;
        }

        try {
            OutputStream outputStream = serialPort.getOutputStream();
            outputStream.write(DataUtil.HexToByteArr("B20000024E0004000F032600C1FE"));
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        TextView view = (TextView)findViewById(R.id.textView);
        view.setOnClickListener((e)->{
            sb = new StringBuilder("");
            view.setText("");
            try {
                OutputStream outputStream = serialPort.getOutputStream();
                outputStream.write(DataUtil.HexToByteArr("B20000024E0004000F032600C1FE"));
                outputStream.flush();
                //点击串口数据集取反
//                flagTty.set(!flagTty.get());
            } catch (IOException err) {
                err.printStackTrace();
            }
        });

        InputStream inputStream = serialPort.getInputStream();
        byte[] readData = new byte[1024];
        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(! (sb==null || view==null)){
                    sb.append (msg.getData().getString("data"));
                    view.setText(sb);
                }
            }
        };
        new Thread(()->{
            while (true) {
                //串口关闭状态false,不去轮询
                if (! flagTty.get()) {
                    continue;
                }
                try {
                    if (inputStream == null) {
                        return;
                    }
                    int size = inputStream.read(readData);
                    if (size>0) {

                        String recinfo = DataUtil.ByteArrToHex(readData,0 ,size);
                        Log.i("llzs", "接收到串口数据:" + (recinfo) );
                        /*将接收到的数据封装进Message中，然后发送给主线程
                         */
                        Message message = new Message();Bundle bundle = new Bundle();
                        Message msg2 = new Message();msg2.what=2;
                        handler1.sendMessage(msg2);
                        bundle.putString("data",(recinfo));message.setData(bundle);handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}